package com.ecole.mines.emargement;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

import com.ecole.mines.model.Cours;
import com.ecole.mines.model.Promotion;
import com.ecole.mines.utils.OnTaskCompleted;
import com.ecole.mines.utils.ParserJSON;
import com.ecole.mines.utils.UtilsString;

public class MainActivity extends FragmentActivity implements OnTaskCompleted {

	private FragmentDetailCours detailCours;
	private FragmentListePromoGroupe mainFragment;
	private ProgressDialog spinnerLoadData;
	private TextView texteEntete;
	private Promotion promoSelectionne;
	private SharedPreferences sharedpreferences;

	@Override
	public void onBackPressed() {

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		//On vérifie si l'application a démarré suite à un arrêt forcé de la tablette
		//sur la partie émargement
		sharedpreferences = getSharedPreferences(UtilsString.MyPREFERENCES,
				Context.MODE_PRIVATE);
		boolean b=sharedpreferences.getBoolean("emargement",false);
		System.out.println("Demarrage forcé "+b);
		/*if(sharedpreferences.getBoolean("emargement",false))
		{
			//TODO Revoir
			Intent i = new Intent(this, EmargementActivity.class);
			//i.putExtra("promo", this.promoSelectionne);
			startActivity(i);
		}*/
		
		detailCours = (FragmentDetailCours) getFragmentManager()
				.findFragmentById(R.id.detail_fragment);
		mainFragment = (FragmentListePromoGroupe) getFragmentManager()
				.findFragmentById(R.id.main_liste_fragment);

		this.texteEntete = (TextView) findViewById(R.id.texteEntete);
		SimpleDateFormat sdf = new SimpleDateFormat("EEEE d MMMM y",
				Locale.FRENCH);
		this.texteEntete.setText(getResources().getString(R.string.ecole) + " "
				+ sdf.format(new Date()));

		if (isNetworkAvailable()) {
			showLoadingDialog();
			new ParserJSON(this).execute("/tablette/first");

			// mainFragment.majListePromo(new
			// ParserJSON(this).parserJSON(null,getAssets()));
		} else {
			Toast.makeText(getApplication(),
					"Aucune connexion internet détectée !", Toast.LENGTH_SHORT)
					.show();
		}
		//mainFragment.majListePromo(new ParserJSON(this).parserJSON(null,
		//		getAssets()));
	}

	private boolean isNetworkAvailable() {
		ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetworkInfo = connectivityManager
				.getActiveNetworkInfo();
		return activeNetworkInfo != null && activeNetworkInfo.isConnected();
	}

	@Override
	public void onTaskCompletedPromo(ArrayList<?> promo) {
		dismissLoadingDialog();
		mainFragment.majListePromo((ArrayList<Promotion>) promo);
		mainFragment.cacherListeCours();
		detailCours.cacherVue();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.menu_emargement, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_power) {
			shutdown_sys();
			return true;
		}

		if (id == R.id.action_home) {
			Intent LaunchIntent = getPackageManager()
					.getLaunchIntentForPackage("com.android.settings");
			startActivity(LaunchIntent);
			return true;
		}

		if (id == R.id.action_refresh) {
			if (isNetworkAvailable()) {
				showLoadingDialog("Chargement",
						"Patientez pendant l'actualisation des données");
				new ParserJSON(this).execute("/tablette/first/force");
			} else {
				Toast.makeText(
						getApplication(),
						"Actualisation impossible! \n "
								+ "Aucune connexion internet détectée",
						Toast.LENGTH_SHORT).show();
			}
		}
		return super.onOptionsItemSelected(item);
	}

	public void showLoadingDialog() {

		if (spinnerLoadData == null) {
			spinnerLoadData = new ProgressDialog(this);
			spinnerLoadData.setTitle("Chargement");
			spinnerLoadData
					.setMessage("Patientez pendant le chargement des données");
		}
		spinnerLoadData.show();
	}

	public void showLoadingDialog(String title, String message) {

		if (spinnerLoadData == null) {
			spinnerLoadData = new ProgressDialog(this);
			spinnerLoadData.setTitle(title);
			spinnerLoadData.setMessage(message);
		}
		spinnerLoadData.show();
	}

	public void dismissLoadingDialog() {
		if (spinnerLoadData != null && spinnerLoadData.isShowing()) {
			spinnerLoadData.dismiss();
		}
	}

	/**
	 * Mets à jour les informations du cours sur le fragment détail
	 * 
	 * @param details
	 *            les informations à afficher à l'utilisateur
	 */
	public void majDetailCours(Promotion p, Cours c) {
		this.promoSelectionne = p;
		this.promoSelectionne.setCours(new ArrayList<Cours>());
		this.promoSelectionne.getCours().add(c);

		detailCours.setCoursAffiche(c);
		detailCours.majDetailsCours();
	}

	public void demarreEmargementActivity() {
		Intent i = new Intent(this, EmargementActivity.class);
		i.putExtra("promo", this.promoSelectionne);

		startActivity(i);
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	void shutdown_sys() {
		try {
			Process proc = Runtime.getRuntime().exec(
					new String[] { "su", "-c", "reboot -p" });
			proc.waitFor();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void onTaskCompletedPin(Boolean resultat) {
		// TODO Auto-generated method stub

	}
}
